package com.sl.diary.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.sl.diary.R;
import com.sl.diary.component.AlbumStorageDirFactory;
import com.sl.diary.component.BaseAlbumDirFactory;
import com.sl.diary.component.DatePickerDialog;
import com.sl.diary.component.FroyoAlbumDirFactory;
import com.sl.diary.db.DBManager;
import com.sl.diary.model.ImageModel;
import com.sl.diary.model.PointModel;
import com.sl.diary.model.TourModel;
import com.sl.diary.model.TravelModel;
import com.sl.diary.util.DLog;
import com.sl.diary.util.Util;

public class A006_MapDetail extends FragmentActivity
						implements OnClickListener,
								OnTouchListener, OnItemClickListener{
	private static String TAG = "A006_MapDetail";
	
	private ImageButton btn_back, btn_save, 
						btn_show_type, btn_camera,
						btn_setting, btn_edit_tour_name,
						btn_edit_description,
						btn_description_next;
	
	private GoogleMap mGoogleMap;
	
	private LinearLayout 	layout_bg_menu, layout_menu;
	private ImageView 		img_icon_tour;
	private TextView 		txt_tour_name, txt_menu_distance_text,
							txt_menu_distance, txt_menu_geo_txt,
							txt_description, txt_from, txt_to;
	
	private EditText		txt_menu_tour_name_edit,
							txt_menu_description_edit;
	
	private RelativeLayout 	layout_menu_geo;
	private ScrollView 		scroll_menu;
	
	private Animation 		fadeInAnim, fadeOutAnim, 
							translateInAnim, translateOutAnim;
	
	private PopupWindow popupWindow;
	
	/** The m current photo path. */
	private String mCurrentPhotoPath;
	private String mThumbnailPhotoPath;
	
	/** The Constant JPEG_FILE_PREFIX. */
	private static final String JPEG_FILE_PREFIX = "IMG_";
	
	/** The Constant JPEG_FILE_SUFFIX. */
	private static final String JPEG_FILE_SUFFIX = ".jpg";
	
	/** The m album storage dir factory. */
	private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
	
	private int DELAY_TIME = 500;
	private boolean isToggle = true;
	
	/** The take picture. */
	private int TAKE_PICTURE 	= 10;
	
	/** The tapped marker. */
	private Marker tappedMarker;
	
	/** The db. */
	private DBManager db;
	
	private TourModel tour;
	private TravelModel travel;
	
	private int TOUR_KIND 	= 1;
	private int TRAVEL_KIND = 2;
	private int kind 		= TOUR_KIND;
	
	/** The date from. */
	private int DATE_FROM 	= 1;
	
	/** The date to. */
	private int DATE_TO 	= 2;
	
	private List<PointModel> pointList = new ArrayList<PointModel>();
	private List<ImageModel> imageList = new ArrayList<ImageModel>();
	
	private static final int MAP_ZOOM_SIZE = 16;
	
	/** The map type. */
	private int[] mapType = {GoogleMap.MAP_TYPE_NORMAL, GoogleMap.MAP_TYPE_SATELLITE,
							GoogleMap.MAP_TYPE_HYBRID, GoogleMap.MAP_TYPE_TERRAIN};
	
	/** The show map type array. */
	private String[] showMapTypeArray = { "Normal", "Satellite", 
										"Satellite and Street",
										"Terrain"};
	
	private enum MenuState {
		HIDING,
		SHOWING, 
		TOUCHING
	}
	
	// Previous touch position
    float prevX = 0;
    float prevY = 0;
	
	// menu is hidden initially
    private MenuState currentMenuState = MenuState.HIDING;
    
    private boolean changeFlag = false;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a006_mapdetail);
        
        db = new DBManager(getApplicationContext());
		db.open();
        initView();
	}
	
	private void initView(){
		btn_back 		= (ImageButton) findViewById(R.id.a006_content_btn_back);
		btn_save 		= (ImageButton) findViewById(R.id.a006_content_btn_save);
		btn_show_type 	= (ImageButton) findViewById(R.id.a006_content_btn_show_type);
		btn_camera 		= (ImageButton) findViewById(R.id.a006_content_btn_camera);
		btn_setting 	= (ImageButton) findViewById(R.id.a006_content_btn_setting);
		btn_edit_tour_name 	= (ImageButton) findViewById(R.id.a006_menu_btn_edit_tour_name);
		btn_edit_description = (ImageButton) findViewById(R.id.a006_menu_btn_edit_description);
		btn_description_next = (ImageButton) findViewById(R.id.a006_menu_btn_next);
		
		SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.a006_fragment_map);
		mGoogleMap = fragment.getMap();
		
		layout_bg_menu = (LinearLayout) findViewById(R.id.layout_bg_menu);
		layout_menu = (LinearLayout) findViewById(R.id.a006_layout_menu);
		
		img_icon_tour = (ImageView) findViewById(R.id.a006_menu_icon_tour);
		txt_tour_name = (TextView) findViewById(R.id.a006_menu_tour_name);
		txt_menu_distance_text 	= (TextView) findViewById(R.id.a006_menu_txt_distance_text);
		txt_menu_distance 		= (TextView) findViewById(R.id.a006_menu_txt_distance);
		txt_menu_geo_txt 		= (TextView) findViewById(R.id.a006_menu_txt_geo_text);
		txt_description 		= (TextView) findViewById(R.id.a006_menu_txt_description);
		txt_from				= (TextView) findViewById(R.id.a006_menu_txt_from);
		txt_to					= (TextView) findViewById(R.id.a006_menu_txt_to);
		
		txt_menu_tour_name_edit = (EditText) findViewById(R.id.a006_menu_tour_name_edit);
		txt_menu_description_edit = (EditText) findViewById(R.id.a006_menu_description_edit);
		
		layout_menu_geo = (RelativeLayout) findViewById(R.id.a006_menu_geo);
		scroll_menu = (ScrollView) findViewById(R.id.a006_scroll_menu);
		
		btn_back.setOnClickListener(this);
		btn_save.setOnClickListener(this);
		btn_show_type.setOnClickListener(this);
		btn_camera.setOnClickListener(this);
		btn_setting.setOnClickListener(this);
		btn_edit_tour_name.setOnClickListener(this);
		btn_edit_description.setOnClickListener(this);
		btn_description_next.setOnClickListener(this);
		txt_from.setOnClickListener(this);
		txt_to.setOnClickListener(this);
		
		layout_bg_menu.setOnTouchListener(this);
		layout_menu.setOnTouchListener(this);
		
		fadeInAnim = new AlphaAnimation(0.0f, 0.8f);
		fadeInAnim.setDuration(DELAY_TIME);
		fadeInAnim.setFillAfter(true);
		
		fadeOutAnim = new AlphaAnimation(0.8f, 0.0f);
		fadeOutAnim.setDuration(DELAY_TIME);
		
		translateInAnim = AnimationUtils.loadAnimation(this, R.anim.left_to_right_in);
		translateInAnim.setDuration(DELAY_TIME);
		translateInAnim.setFillAfter(true);
		
		translateOutAnim = AnimationUtils.loadAnimation(this, R.anim.right_to_left_out);
		translateOutAnim.setDuration(DELAY_TIME);
		
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
		} else {
			mAlbumStorageDirFactory = new BaseAlbumDirFactory();
		}
		
		tour = db.getTour("1");
		pointList = db.getAllPointOfTour("1");
		
		for(PointModel point: pointList) {
			mGoogleMap.addMarker(new MarkerOptions()
					.position(new LatLng(point.getLatitude(), point.getLongitude()))
					.snippet(point.getId()));
			imageList.addAll(db.getAllImageOfPoint(point.getId()));
		}
		
		if(pointList.size() > 0) {
			CameraUpdate camera = CameraUpdateFactory
					.newCameraPosition(new CameraPosition.Builder()
						.target(new LatLng(pointList.get(0).getLatitude(), pointList.get(0).getLongitude()))
						.zoom(MAP_ZOOM_SIZE).build());
			mGoogleMap.animateCamera(camera);
		}
		setMenu();
	}
	
	private void setMenu(){
		layout_menu_geo.setVisibility(View.GONE);
		if(tour.getType() == TourModel.POINT) {
			img_icon_tour.setImageResource(R.drawable.icon_geo_white);
			txt_menu_distance_text.setText(R.string.radius);
			txt_menu_distance.setText(tour.getRadius() + 
				String.format(getResources().getString(R.string.a006_unit_metre)));
			layout_menu_geo.setVisibility(View.VISIBLE);
		} else if(tour.getType() == TourModel.LINE) {
			img_icon_tour.setImageResource(R.drawable.icon_tour_white);
			txt_menu_distance_text.setText(R.string.a006_distance);
			txt_menu_distance.setText(tour.getDistance() + 
					String.format(getResources().getString(R.string.a006_unit_metre)));
		} else if(tour.getType() == TourModel.AREA) {
			img_icon_tour.setImageResource(R.drawable.icon_area_white);
			txt_menu_distance_text.setText(R.string.a006_area);
			
			SpannableStringBuilder cs = new SpannableStringBuilder("2");
			cs.setSpan(new RelativeSizeSpan((float)0.75), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			
			txt_menu_distance.setText(Html.fromHtml(tour.getArea() + 
					String.format(getResources().getString(R.string.a006_unit_metre))
					+ "<sup><small>2</small></sup>"));
		}
		
		txt_tour_name.setText(tour.getName());
		txt_menu_tour_name_edit.setText(tour.getName());
		
		txt_description.setText(getDescriptionForTextView());
		txt_menu_description_edit.setText(tour.getDescription());
		 
		txt_from.setText(Util.convertDateToString(tour.getDeparture_date()));
		txt_to.setText(Util.convertDateToString(tour.getEnd_date()));
	}
	
	private String getDescriptionForTextView(){
		String des = "";
		if(tour.getDescription().length() > 50) {
			des = tour.getDescription().substring(0, 49) 
					+ String.format(getResources().getString(R.string.a006_three_dots));
		} else {
			des = tour.getDescription();
		}
		
		return des;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.a006_content_btn_setting:
			toggleMenu();
			break;
		case R.id.a006_content_btn_back:
			if(!changeFlag)
				finish();
			else {
				showDialogSaveChanges();
			}
			break;
		case R.id.a006_content_btn_camera:
			// take camera
			Bitmap bmp = takeScreenshot();
			saveBitmap(bmp);
			break;
		case R.id.a006_content_btn_show_type:
			// show type
			setPopup(showMapTypeArray, v);
			break;
		case R.id.a006_content_btn_save:
			saveData();
			finish();
			break;
		case R.id.a006_menu_btn_edit_tour_name:
			
			if(txt_menu_tour_name_edit.getVisibility() == View.GONE) {
				txt_tour_name.setVisibility(View.GONE);
				txt_menu_tour_name_edit.setVisibility(View.VISIBLE);
				btn_edit_tour_name.setImageResource(R.drawable.check_btn);
			} else {
				txt_tour_name.setVisibility(View.VISIBLE);
				txt_menu_tour_name_edit.setVisibility(View.GONE);
				btn_edit_tour_name.setImageResource(R.drawable.a003_btn_edit);
				
				tour.setName(txt_menu_tour_name_edit.getText().toString());
				txt_tour_name.setText(tour.getName());
			}
			break;
		case R.id.a006_menu_btn_edit_description:
			if(txt_menu_description_edit.getVisibility() == View.GONE) {
				txt_description.setVisibility(View.GONE);
				txt_menu_description_edit.setVisibility(View.VISIBLE);
				btn_edit_description.setImageResource(R.drawable.check_btn);
			} else {
				txt_description.setVisibility(View.VISIBLE);
				txt_menu_description_edit.setVisibility(View.GONE);
				btn_edit_description.setImageResource(R.drawable.a003_btn_edit);
				
				tour.setDescription(txt_menu_description_edit.getText().toString());
				txt_tour_name.setText(getDescriptionForTextView());
			}
			break;
		case R.id.a006_menu_btn_next:
			showDialogDescription();
			break;
		case R.id.a006_menu_txt_from:
			showDatePickerDialog(txt_from, DATE_FROM);
			break;
		case R.id.a006_menu_txt_to:
			showDatePickerDialog(txt_to, DATE_TO);
			break;
		default:
			break;
		}
	}
	
	private void saveData(){
		db.updateTour(tour);
	}
	
	private void showDialogDescription() {
		final Dialog dialog = new Dialog(this);
		dialog.setTitle(R.string.lbl_description);
		dialog.setContentView(getLayoutInflater().
			     inflate(R.layout.a006_dialog_description, null));
		
		TextView text = (TextView) dialog.findViewById(R.id.txt_description);
		text.setText(tour.getDescription());
		
		Button btn_close = (Button) dialog.findViewById(R.id.btn_close);
		btn_close.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		
		dialog.show();
	}
	
	/**
	 * show date picker dialog.
	 *
	 * @param viewId the id of departure/end date image button
	 * @param dateButton the date button
	 * @param dateType the date type
	 */
	private final void showDatePickerDialog(final TextView viewId, final int dateType) {
		final Calendar calendar = Calendar.getInstance();
		DatePickerDialog datePickerDialog = new DatePickerDialog(
				A006_MapDetail.this, R.style.DialogSlideAnim, calendar,
				null, new DatePickerDialog.DatePickerListner() {

					@Override
					public void OnDoneButton(Dialog dialog, Calendar c) {

						calendar.set(Calendar.YEAR, c.get(Calendar.YEAR));
						calendar.set(Calendar.MONTH, c.get(Calendar.MONTH));
						calendar.set(Calendar.DAY_OF_MONTH,
								c.get(Calendar.DAY_OF_MONTH));

						Date selectedDate = new Date(
								calendar.get(Calendar.YEAR) - 1900,
								calendar.get(Calendar.MONTH),
								calendar.get(Calendar.DAY_OF_MONTH));
						
						if(dateType == DATE_FROM)
							tour.setDeparture_date(selectedDate);
						else
							tour.setEnd_date(selectedDate);
							
						viewId.setText(Util.convertDateToString(selectedDate));
						viewId.setVisibility(View.VISIBLE);
						dialog.dismiss();
					}

					@Override
					public void OnCancelButton(Dialog dialog) {
						dialog.dismiss();
					}
				});
		// show dialog
		datePickerDialog.show();
	}
	
	private void showDialogSaveChanges(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setMessage(R.string.a006_message_dialog);
		// Add the buttons
		builder.setPositiveButton(R.string.lbl_yes, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               saveData();
		               finish();
		           }
		       });
		builder.setNegativeButton(R.string.lbl_no, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               finish();
		           }
		       });
		
		// Create the AlertDialog
		AlertDialog dialog = builder.create();
		dialog.show();
	}
	
	/**
	 * Sets the popup.
	 *
	 * @param data the data
	 * @param view the view
	 */
	private void setPopup(String[] data, View view){
		LayoutInflater layoutInflater 
							= (LayoutInflater)getBaseContext()
							.getSystemService(LAYOUT_INFLATER_SERVICE);  
		View popupView = layoutInflater.inflate(R.layout.layout_popup_shop_map_type, null);  
		popupWindow = new PopupWindow(
				popupView, 
				LayoutParams.WRAP_CONTENT,  
				LayoutParams.WRAP_CONTENT);
		
		ListView list = (ListView) popupView.findViewById(R.id.list_show);
		list.setAdapter(new ArrayAdapter<String>(this, R.layout.layout_popup_item, R.id.txt_item, data));
		list.setOnItemClickListener(this);
		
		popupWindow.setTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setTouchInterceptor(new View.OnTouchListener() {
	        public boolean onTouch(View v, MotionEvent event) {
	            if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
	            	popupWindow.dismiss();
	                return true;
	            }
	            return false;
	        }
	    });

		popupWindow.showAsDropDown(view, -50, 0);
	}
	
	private Bitmap takeScreenshot() {
		View rootView = findViewById(android.R.id.content).getRootView();
		rootView.setDrawingCacheEnabled(true);
		return rootView.getDrawingCache();
	}

	private void saveBitmap(Bitmap bitmap) {
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		
		File imagePath = new File(Environment.getExternalStorageDirectory() + "/DiaryTravel/" + imageFileName + "_screenshot.png");
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(imagePath);
			bitmap.compress(CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			Log.e("GREC", e.getMessage(), e);
		} catch (IOException e) {
			Log.e("GREC", e.getMessage(), e);
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// getRawX returns X touch point corresponding to screen
        // getX sometimes returns screen X, sometimes returns content View X
        int curX = (int)event.getRawX();
        switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				prevX = curX;
	            return true;
	        case MotionEvent.ACTION_MOVE:
	        	float x = event.getRawX();
	        	float diffX = x - prevX;
	        	prevX = x;
	        	
	        	if(layout_menu.getLeft() >= 0 && diffX > 0) {
	        		return false;
	        	}

	        	if(layout_menu.getLeft() + diffX >= 0) {
	        		diffX = -layout_menu.getLeft();
	        	}
	        	
	        	if(Math.abs(diffX) < 10 
	        			&& currentMenuState != MenuState.TOUCHING
	        			&& v.getId() == R.id.a006_scroll_menu) {
	        		isToggle = true;
	        		return true;
	        	} else 
	        		isToggle = false;
	        	
	        	currentMenuState = MenuState.TOUCHING;
	        	layout_menu.offsetLeftAndRight((int) diffX);

	        	float alpha = (float) ((layout_menu.getRight() * 0.8)/layout_menu.getWidth());
	        	AlphaAnimation animation = new AlphaAnimation(alpha, alpha);
        		animation.setDuration(0);
        		animation.setFillAfter(true);
        		layout_bg_menu.startAnimation(animation);
	        	return true;
	        case MotionEvent.ACTION_UP:
	        	if(!isToggle) {
	        		isToggle = true;
	        		startScrollIfNeeded();
	        	} else
	        		toggleMenu();
				break;
			default:
				break;
		}
        return false;
	}
	
	private void toggleMenu(){
		if(currentMenuState == MenuState.HIDING) {
			layout_bg_menu.setVisibility(View.VISIBLE);
			layout_bg_menu.startAnimation(fadeInAnim);
			
			layout_menu.setVisibility(View.VISIBLE);
			layout_menu.startAnimation(translateInAnim);
			
			currentMenuState = MenuState.SHOWING;
		} else {
			layout_bg_menu.startAnimation(fadeOutAnim);
			layout_menu.startAnimation(translateOutAnim);
			
			layout_menu.setVisibility(View.GONE);
			layout_bg_menu.setVisibility(View.GONE);
			currentMenuState = MenuState.HIDING;
		}
	}
	
	private void startScrollIfNeeded(){
		if(layout_menu.getRight() >= layout_menu.getWidth()/2) {
			layout_menu.offsetLeftAndRight((int) -layout_menu.getLeft());
			currentMenuState = MenuState.SHOWING;
		} else {
			toggleMenu();
		}
	}
	
	@Override
    public void onBackPressed() {
        if (currentMenuState == MenuState.SHOWING) {
            toggleMenu();
        } else {
            super.onBackPressed();
        }
    }
	
	
	
	//////////////////////// used for take photo
	/**
	 * Handle big camera photo.
	 */
	private void handleBigCameraPhoto() {
		dispatchTakePictureIntent();
		if (mCurrentPhotoPath != null) {
//			db.addImage(new ImageModel("1", mCurrentPhotoPath, tappedMarker.getSnippet()));
			
			tappedMarker.setIcon(BitmapDescriptorFactory
								.fromBitmap(Util.decodeImageMarker(mCurrentPhotoPath, this)));
			
			mCurrentPhotoPath = null;
			
		}

	}
	
	/* (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
		if (requestCode == TAKE_PICTURE) {
			if (resultCode == RESULT_OK) {
				handleBigCameraPhoto();
			}
		}
	}
	
	/**
	 * Dispatch take picture intent.
	 */
	private void dispatchTakePictureIntent() {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		File f = null;
		
		try {
			f = setUpPhotoFile();
			mCurrentPhotoPath = f.getAbsolutePath();
			takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		} catch (IOException e) {
			e.printStackTrace();
			f = null;
			mCurrentPhotoPath = null;
		}
		
		startActivityForResult(takePictureIntent, TAKE_PICTURE);
	}
	
	/**
	 * Sets the up photo file.
	 *
	 * @return the file
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	private File setUpPhotoFile() throws IOException {
		
		File f = createImageFile();
		File fThumbnail = createImageFile();
		mCurrentPhotoPath = f.getAbsolutePath();
		mThumbnailPhotoPath = fThumbnail.getAbsolutePath();
		return f;
	}

	/**
	 * Creates the image file.
	 *
	 * @return the file
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	private File createImageFile() throws IOException {
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir("DiaryTravel");
		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
		return imageF;
	}
	
	/**
	 * Gets the album dir.
	 *
	 * @return the album dir
	 */
	private File getAlbumDir(String name) {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			
			storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(name);

			if (storageDir != null) {
				if (! storageDir.mkdirs()) {
					if (! storageDir.exists()){ 
						DLog.d("CameraSample", "failed to create directory");
						return null;
					}
				}
			}
			
		} else {
			DLog.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
		}
		
		return storageDir;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		mGoogleMap.setMapType(mapType[position]);
		popupWindow.dismiss();
	}

}
